package com.ruoyi.system.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.SysMsgConstans;
import com.ruoyi.common.core.enums.OrderStatusEnum;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.OrderSelectRequestDTO;
import com.ruoyi.system.domain.dto.SysOrderResponseDTO;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.mapper.SysOrderMapper;
import com.ruoyi.system.vo.req.order.*;
import com.ruoyi.system.vo.resp.SysOrderRespVo;
import com.ruoyi.system.vo.resp.SysOrderSpeedRespVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author xdh
* @description 针对表【sys_order】的数据库操作Service实现
* @createDate 2024-07-01 17:59:34
*/
@Service
@Slf4j
public class SysOrderServiceImpl extends ServiceImpl<SysOrderMapper, SysOrder>
    implements SysOrderService{

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysOrderMapper sysOrderMapper;


    @Autowired
    private SysOrderPService sysOrderPService;

    @Autowired
    private SysOrderStrikeDroneService sysOrderStrikeDroneService;

    @Autowired
    private SysOrderStrikeInvalidService sysOrderStrikeInvalidService;

    @Autowired
    private SysOrderStrikeValidService sysOrderStrikeValidService;

    @Autowired
    private SysOrderDeptService sysOrderDeptService;

    @Autowired
    private ISysDeptService iSysDeptService;


    @Autowired
    private SysOrderSpeedService sysOrderSpeedService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public IPage<SysOrderRespVo> listPage(OrderSelectRequestVO req) {
        if(req.getOrderStatus()==0){
            req.setOrderStatus(null);
        }
//        LoginUser loginUser = tokenService.getLoginUser();
        Long deptId = tokenService.getLoginUser().getSysUser().getDeptId();

        IPage<SysOrder> objectPage = new Page<>(req.getPageNum(), req.getPageSize());
        OrderSelectRequestDTO orderSelectRequestDTO = toDo(req);

        return sysOrderMapper.pageBySql(objectPage,orderSelectRequestDTO,deptId);


//        return this.page(new Page<>(req.getPageNum(),req.getPageSize()),new LambdaQueryWrapper<SysOrder>()
//                .eq(SysOrder::getOrderStatus,1)
//                .like(StringUtils.isNoneBlank(req.getOrder_keyword()),SysOrder::getOrderBuyerName,req.getOrder_keyword())
//                .like(StringUtils.isNoneBlank(req.getOrder_keyword()),SysOrder::getOrderHarverName,req.getOrder_keyword())
//                .like(StringUtils.isNoneBlank(req.getOrder_keyword()),SysOrder::getOrderBuyerTel,req.getOrder_keyword())
//                .like(StringUtils.isNoneBlank(req.getOrder_keyword()),SysOrder::getOrderHarverTel,req.getOrder_keyword())
//                .like(StringUtils.isNoneBlank(req.getOrder_keyword()),SysOrder::getOrderBuyerIndo,req.getOrder_keyword())
//                .like(StringUtils.isNoneBlank(req.getOrder_keyword()),SysOrder::getOrderHarverAddress,req.getOrder_keyword())
//                .like(StringUtils.isNoneBlank(req.getOrder_keyword()),SysOrder::getOrderGoods,req.getOrder_keyword())
//        );
    }

    @Override
    public List<SysOrderRespVo> synerList(Integer orderId) {

        SysDept dept = tokenService.getLoginUser().getSysUser().getDept();
        if(dept==null){
            throw  new ServiceException("当前用户未分配组织！");
        }
        SysOrder sysOrder = this.getById(orderId);

        return sysOrderMapper.listBySql(orderId,sysOrder.getOrderHarverTel(),sysOrder.getOrderHarverAddress(),dept.getDeptId());
    }
    @Autowired
    private IDataScreeningPersonnelControlService dataScreeningPersonnelControlService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HashMap<String,Integer> insert(OrderStrikeRequestVO requestVO) {
        synchronized (requestVO.getOrderId().toString().intern()) {
            //判断是否被核查
            SysOrder byId = getById(requestVO.getOrderId());
            if(byId.getOrderStrikeDeptId() != null){
                throw  new ServiceException("当前订单已核查，请勿重复提交！");
            }
            //判断是否能核查
            SysUser sysUser = tokenService.getLoginUser().getSysUser();
            SysDept dept = sysUser.getDept();
            if(dept==null){
                throw  new ServiceException("当前用户未分配组织！");
            }
            if(dept.getDeptLevel() != 3){
                throw  new ServiceException("当前用户不属于区县级单位，不能核查！");
            }

            Long deptId = dept.getDeptId();
            Date date = new Date();


            //核查反馈信息新增
            OrderStrikeRequestVO.OrderStrikeInfo orderStrikeInfo = requestVO.getOrderStrikeInfo();
            SysOrderStrikeInvalid sysOrderStrikeInvalid = new SysOrderStrikeInvalid();
            sysOrderStrikeInvalid.setOrderId(requestVO.getOrderId());
            sysOrderStrikeInvalid.setStatus(1);
            sysOrderStrikeInvalid.setCreTime(date);
            sysOrderStrikeInvalid.setRemark(orderStrikeInfo.getRemark());
            sysOrderStrikeInvalid.setDeptId(deptId.intValue());



            if(requestVO.getIsVaild() == 1){
                //无人机信息信息
                if(!requestVO.getValidDroneInfo().isEmpty()){
                    for (OrderStrikeRequestVO.ValidDroneInfo validDroneInfo : requestVO.getValidDroneInfo()) {
                        SysOrderStrikeDrone sysOrderStrikeDrone = new SysOrderStrikeDrone();
                        sysOrderStrikeDrone.setDroneBrand(validDroneInfo.getDroneBrand());
                        sysOrderStrikeDrone.setDroneModel(validDroneInfo.getDroneModel());
                        sysOrderStrikeDrone.setDroneCode(validDroneInfo.getDroneCode());
                        sysOrderStrikeDrone.setDroneUse(validDroneInfo.getDroneUse());
                        sysOrderStrikeDrone.setDronePurpose(validDroneInfo.getDronePurpose());
                        sysOrderStrikeDrone.setDroneRemark(validDroneInfo.getDroneRemark());
                        sysOrderStrikeDrone.setCreTime(date);
                        sysOrderStrikeDrone.setStatus(1);
                        sysOrderStrikeDrone.setOrderId(requestVO.getOrderId());
                        sysOrderStrikeDroneService.save(sysOrderStrikeDrone);
                    }
                }

                //核查反馈有效信息新增
                if(requestVO.getValidDroneInfo()!=null){
                    OrderStrikeRequestVO.ValidUserInfo validUserInfo = requestVO.getValidUserInfo();
                    SysOrderStrikeValid sysOrderStrikeValid = new SysOrderStrikeValid();
                    sysOrderStrikeValid.setOrderStrikeUserName(validUserInfo.getOrderStrikeUserName());
                    sysOrderStrikeValid.setOrderStrikeUserAddress(validUserInfo.getOrderStrikeUserAddress());
                    sysOrderStrikeValid.setOrderStrikeUserIndo(validUserInfo.getOrderStrikeUserIndo());
                    sysOrderStrikeValid.setOrderStrikeUserWork(validUserInfo.getOrderStrikeUserWork());
                    sysOrderStrikeValid.setOrderStrikeUserOccupation(validUserInfo.getOrderStrikeUserOccupation());
                    sysOrderStrikeValid.setOrderStrikeUserTel(validUserInfo.getOrderStrikeUserTel());
                    sysOrderStrikeValid.setStatus(1);
                    sysOrderStrikeValid.setCreTime(date);
                    sysOrderStrikeValid.setOrderId(requestVO.getOrderId());
                    sysOrderStrikeValidService.save(sysOrderStrikeValid);
                }
                //有效反馈信息
                sysOrderStrikeInvalid.setChangPoliceId(orderStrikeInfo.getChangPoliceId());
                sysOrderStrikeInvalid.setCensusPoliceName(orderStrikeInfo.getCensusPoliceId());
                sysOrderStrikeInvalid.setXjFlag(orderStrikeInfo.getXjFlag());
                sysOrderStrikeInvalid.setIsValid(1);
                sysOrderStrikeInvalidService.save(sysOrderStrikeInvalid);

            }else if(requestVO.getIsVaild() == 0){
                //无效反馈信息
                sysOrderStrikeInvalid.setRemark(orderStrikeInfo.getRemark());
                sysOrderStrikeInvalid.setIsValid(0);
                sysOrderStrikeInvalidService.save(sysOrderStrikeInvalid);
            }else{
                throw new ServiceException("请选择是否为有效信息！");
            }

            //协同记录新增
            if(requestVO.getOrderIds().length > 0){
                for (Integer orderId : requestVO.getOrderIds()) {
                    //判断是否被核查
                    SysOrder byId1 = getById(orderId);
                    if(byId1.getOrderStrikeDeptId() != null){
                        throw  new ServiceException("协同订单编码"+byId1.getOrderCode()+"已被核查，无法重复核查！");
                    }
                    SysOrderP sysOrderP = new SysOrderP();
                    sysOrderP.setOrderPid(requestVO.getOrderId());
                    sysOrderP.setOrderId(orderId);
                    sysOrderP.setCreTime(date);
                    sysOrderP.setStatus(1);
                    sysOrderPService.save(sysOrderP);

                    //协同订单状态修改
                    List<SysOrderDept> orderDeptList = sysOrderDeptService.list(new LambdaQueryWrapper<SysOrderDept>().select(SysOrderDept::getId).eq(SysOrderDept::getStatus, 1)
                            .eq(SysOrderDept::getOrderId, orderId).eq(SysOrderDept::getOrderStatus, 2));

                    if(!orderDeptList.isEmpty()){
                        for (SysOrderDept sysOrderDept : orderDeptList) {
                            sysOrderDept.setOrderStatus(3);//已核查
                            sysOrderDept.setUpdTime(date);
                            sysOrderDeptService.updateById(sysOrderDept);
                        }
                    }else{
                        throw  new ServiceException("协同订单异常，请联系后台管理人员！");
                    }



                    //协同订单核查信息修改
                    SysOrder sysOrder = new SysOrder();
                    sysOrder.setId(orderId);
                    sysOrder.setOrderStrikeTime(date);
                    sysOrder.setOrderStrikeDeptId(dept.getDeptId().intValue());
                    sysOrder.setOrderStrikeDeptname(dept.getDeptName());
                    sysOrder.setOrderStrikeUsername(sysUser.getNickName());
                    sysOrder.setOrderStrikeUserId(sysUser.getUserId().intValue());
                    this.updateById(sysOrder);


                    //核查进度新增
                    sysOrderSpeedService.create(dept.getDeptLevel(),orderId,date);
                }
            }

            //本订单状态修改
            List<SysOrderDept> sysOrderDepts = sysOrderDeptService.list(new LambdaQueryWrapper<SysOrderDept>().eq(SysOrderDept::getStatus, 1)
                    .eq(SysOrderDept::getOrderId, requestVO.getOrderId()));
            if(sysOrderDepts.isEmpty()){
                throw  new ServiceException("订单异常，请联系后台管理人员！");
            }
            //本订单
            for (SysOrderDept sysOrderDept : sysOrderDepts) {
                sysOrderDept.setOrderStatus(3);//已核查
                sysOrderDept.setUpdTime(date);
                sysOrderDeptService.updateById(sysOrderDept);

                //核查进度新增
                sysOrderSpeedService.create(dept.getDeptLevel(),requestVO.getOrderId(),date);
            }
            SysOrder sysOrder = new SysOrder();
            sysOrder.setId(requestVO.getOrderId());
            sysOrder.setOrderStrikeTime(date);
            sysOrder.setOrderStrikeDeptId(dept.getDeptId().intValue());
            sysOrder.setOrderStrikeDeptname(dept.getDeptName());
            sysOrder.setOrderStrikeUsername(sysUser.getNickName());
            sysOrder.setOrderStrikeUserId(sysUser.getUserId().intValue());
            this.updateById(sysOrder);

            return dataScreeningPersonnelControlService.exportGK(requestVO);
        }

        //return true;

    }

    @Override
    public OrderStrikeResponseVO detail(Integer orderId) {

        OrderStrikeResponseVO orderStrikeResponseVO = new OrderStrikeResponseVO();

        SysOrder newOrder = this.getOne(new LambdaQueryWrapper<SysOrder>().eq(SysOrder::getId,orderId).select(SysOrder::getOrderCode));
        //查询是否为协同订单
        SysOrderP sysOrderP = sysOrderPService.getOne(new LambdaQueryWrapper<SysOrderP>().eq(SysOrderP::getStatus, 1).eq(SysOrderP::getOrderId, orderId));
        if(sysOrderP != null){
            orderId =  sysOrderP.getOrderPid();
        }
        OrderStrikeResponseVO.OrderStrikeInfo orderStrikeInfo = new OrderStrikeResponseVO.OrderStrikeInfo();
        SysOrder byId = this.getById(orderId);
        if(byId != null){
            SysOrderRespVo sysOrderRespVo = new SysOrderRespVo();
            sysOrderRespVo.setOrderCode(newOrder.getOrderCode());
            sysOrderRespVo.setOrderBuyerName(byId.getOrderBuyerName());
            sysOrderRespVo.setOrderBuyerIndo(byId.getOrderBuyerIndo());
            sysOrderRespVo.setOrderBuyerTel(byId.getOrderBuyerTel());
            sysOrderRespVo.setOrderTime(byId.getOrderTime());
            sysOrderRespVo.setOrderGoods(byId.getOrderGoods());
            sysOrderRespVo.setOrderHarverName(byId.getOrderHarverName());
            sysOrderRespVo.setOrderHarverTel(byId.getOrderHarverTel());
            sysOrderRespVo.setOrderHarverAddress(byId.getOrderHarverAddress());
//            sysOrderRespVo.setOrderStrikeDeptname(byId.getOrderStrikeDeptname());
//            sysOrderRespVo.setOrderStrikeUsername(byId.getOrderStrikeUsername());
//            sysOrderRespVo.setOrderStrikeDeptId(byId.getOrderStrikeDeptId());
//            sysOrderRespVo.setOrderStrikeUserId(byId.getOrderStrikeUserId());
//            sysOrderRespVo.setOrderStrikeTime(byId.getOrderStrikeTime());
            orderStrikeResponseVO.setSysOrderRespVo(sysOrderRespVo);

            orderStrikeInfo.setOrderStrikeTime(byId.getOrderStrikeTime());
            orderStrikeInfo.setOrderStrikeDeptname(byId.getOrderStrikeDeptname());
            orderStrikeInfo.setOrderStrikeUsername(byId.getOrderStrikeUsername());
        }




        //查询是否为有效订单
        SysOrderStrikeInvalid one = sysOrderStrikeInvalidService.getOne(new LambdaQueryWrapper<SysOrderStrikeInvalid>()
                .eq(SysOrderStrikeInvalid::getOrderId, orderId).eq(SysOrderStrikeInvalid::getStatus,1));


        if(one!=null){
            orderStrikeInfo.setRemark(one.getRemark());

            if(one.getIsValid() == 0){
                orderStrikeResponseVO.setOrderStrikeInfo(orderStrikeInfo);
                orderStrikeResponseVO.setIsValid(0);
            }else if(one.getIsValid() == 1){
                SysDept sysDept = iSysDeptService.selectDeptById(Long.valueOf(one.getChangPoliceId()));
                orderStrikeInfo.setChangPoliceName(sysDept.getDeptName());
                orderStrikeInfo.setCensusPoliceName(one.getCensusPoliceName());
                orderStrikeInfo.setXjFlag(one.getXjFlag());

                orderStrikeResponseVO.setOrderStrikeInfo(orderStrikeInfo);
                orderStrikeResponseVO.setIsValid(1);
                //被排查人员
                SysOrderStrikeValid sysOrderStrikeValid = sysOrderStrikeValidService.getOne(new LambdaQueryWrapper<SysOrderStrikeValid>()
                        .eq(SysOrderStrikeValid::getOrderId, orderId).eq(SysOrderStrikeValid::getStatus,1));
                if(sysOrderStrikeValid!=null){
                    OrderStrikeRequestVO.ValidUserInfo validUserInfo = new OrderStrikeRequestVO.ValidUserInfo();
                    validUserInfo.setOrderStrikeUserName(sysOrderStrikeValid.getOrderStrikeUserName());
                    validUserInfo.setOrderStrikeUserAddress(sysOrderStrikeValid.getOrderStrikeUserAddress());
                    validUserInfo.setOrderStrikeUserIndo(sysOrderStrikeValid.getOrderStrikeUserIndo());
                    validUserInfo.setOrderStrikeUserWork(sysOrderStrikeValid.getOrderStrikeUserWork());
                    validUserInfo.setOrderStrikeUserOccupation(sysOrderStrikeValid.getOrderStrikeUserOccupation());
                    validUserInfo.setOrderStrikeUserTel(sysOrderStrikeValid.getOrderStrikeUserTel());
                    orderStrikeResponseVO.setValidUserInfo(validUserInfo);
                }
                //无人机
                List<SysOrderStrikeDrone> list = sysOrderStrikeDroneService.list(
                        new LambdaQueryWrapper<SysOrderStrikeDrone>()
                                .eq(SysOrderStrikeDrone::getOrderId, orderId)
                                .eq(SysOrderStrikeDrone::getStatus,1));
                if(!list.isEmpty()){
                    List<OrderStrikeRequestVO.ValidDroneInfo> validDroneInfos = new ArrayList<>();
                    for (SysOrderStrikeDrone sysOrderStrikeDrone : list) {
                        OrderStrikeRequestVO.ValidDroneInfo validDroneInfo = new OrderStrikeRequestVO.ValidDroneInfo();
                        validDroneInfo.setDroneBrand(sysOrderStrikeDrone.getDroneBrand());
                        validDroneInfo.setDroneModel(sysOrderStrikeDrone.getDroneModel());
                        validDroneInfo.setDroneCode(sysOrderStrikeDrone.getDroneCode());
                        validDroneInfo.setDroneUse(sysOrderStrikeDrone.getDroneUse());
                        validDroneInfo.setDroneUseGet(sysOrderStrikeDrone.getDroneUse()==0?"本人使用":"单位使用");
                        validDroneInfo.setDronePurpose(sysOrderStrikeDrone.getDronePurpose());
                        validDroneInfo.setDroneRemark(sysOrderStrikeDrone.getDroneRemark());
                        validDroneInfos.add(validDroneInfo);
                    }
                    orderStrikeResponseVO.setValidDroneInfo(validDroneInfos);
                }

            }

        }



        return orderStrikeResponseVO;
    }

    @Autowired
    private SysMsgService sysMsgService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean dispense(OrderDispenseRequestVO requestVO) {

        SysDept dept = tokenService.getLoginUser().getSysUser().getDept();


        if(dept == null){
            throw  new ServiceException("当前用户未分配组织！");
        }

        if(dept.getDeptLevel() == 3){
            throw new ServiceException("当前用户组织级别无法进行派单操作！");
        }



        Date date = new Date();
        if(requestVO.getOrders().length > 0 && requestVO.getDept_id()!=null){
            for (Integer orderId : requestVO.getOrders()) {

                if(dept.getDeptLevel() != 3 ){
                    SysOrderSpeed one = sysOrderSpeedService.getOne(new LambdaQueryWrapper<SysOrderSpeed>()
                            .eq(SysOrderSpeed::getStatus, 1)
                            .eq(SysOrderSpeed::getDeptId, dept.getDeptId())
                            .eq(SysOrderSpeed::getOrderId, orderId)
                            .eq(SysOrderSpeed::getPushLevel,dept.getDeptLevel()));
                    if(one!=null){
                        throw  new ServiceException("当前订单已分发，无法再次分发！");
                    }
                }

                SysOrderDept sysOrderDept = new SysOrderDept();
                sysOrderDept.setOrderId(orderId);
                sysOrderDept.setDeptId(requestVO.getDept_id());
                sysOrderDept.setStatus(1);
                sysOrderDept.setCreTime(new Date());
                sysOrderDept.setOrderStatus(1);
                if(dept.getDeptLevel() == 2){
                    sysOrderDept.setOrderStatus(2);
                }
                sysOrderDept.setDeptPid(dept.getDeptId());
                sysOrderDeptService.save(sysOrderDept);

                SysOrderDept one = sysOrderDeptService.getOne(new LambdaQueryWrapper<SysOrderDept>().eq(SysOrderDept::getStatus, 1)
                        .eq(SysOrderDept::getOrderId, orderId).eq(SysOrderDept::getDeptId, dept.getDeptId()));

                if(one == null){
                    throw  new ServiceException("订单分发异常，请联系后台管理人员！");
                }
                one.setOrderStatus(2);//待核查
                one.setUpdTime(date);
                sysOrderDeptService.updateById(one);

                if(dept.getDeptLevel() == 2){
                   //修改上级单位状态为待核查
                    SysOrderDept sysOrderDept1 = new SysOrderDept();
                    sysOrderDept1.setOrderStatus(2);//待核查
                    sysOrderDept1.setUpdTime(date);
                    sysOrderDeptService.update(sysOrderDept1,new LambdaQueryWrapper<SysOrderDept>()
                            .eq(SysOrderDept::getOrderStatus,1).eq(SysOrderDept::getDeptId,one.getDeptPid())
                            .eq(SysOrderDept::getOrderId,orderId)
                    );

                }

                //分派订单
                sysOrderSpeedService.create(dept.getDeptLevel(),orderId,date);


            }



            List<Integer> userIds = sysUserMapper.selectUserIdByDeptId(requestVO.getDept_id().intValue());
            if(!userIds.isEmpty()){
                for (Integer userId : userIds) {
                    String msg = "";
                    if(dept.getDeptLevel().intValue() == 1){
                         msg = String.format(SysMsgConstans.ORDER_CHECK_CONTENT, dept.getDeptName(), requestVO.getOrders().length, "待分发");
                    }
                    if(dept.getDeptLevel().intValue() == 2){
                        msg = String.format(SysMsgConstans.ORDER_CHECK_CONTENT, dept.getDeptName(), requestVO.getOrders().length, "待核查");
                    }

                    sysMsgService.orderCheck(requestVO.getDept_id().intValue(),userId,msg);
                    log.info("===============消息新增================");
                }


            }
            return true;
        }
        return false;





    }

    @Override
    public List<OrderDeptResponseVO> deptListById() {

        Long deptId = tokenService.getLoginUser().getSysUser().getDeptId();
        if(deptId == null){
            throw  new ServiceException("当前用户未分配组织！");
        }

        return iSysDeptService.listByParendId(deptId);


    }

    @Override
    public OrderResponseVO data() {
        SysDept dept = tokenService.getLoginUser().getSysUser().getDept();
        if (dept == null) {
            throw new ServiceException("当前用户未分配组织！");
        }

        OrderResponseVO orderResponseVO = new OrderResponseVO();
        Integer orderTotal = sysOrderDeptService.count(new LambdaQueryWrapper<SysOrderDept>()
                .eq(SysOrderDept::getStatus, 1).eq(SysOrderDept::getDeptId, dept.getDeptId()));
        orderResponseVO.setOrderTotal(orderTotal);

        Integer inStrikeNum = sysOrderDeptService.count(new LambdaQueryWrapper<SysOrderDept>()
                .eq(SysOrderDept::getStatus, 1).eq(SysOrderDept::getDeptId, dept.getDeptId()).eq(SysOrderDept::getOrderStatus, 2));

        orderResponseVO.setInStrikeNum(inStrikeNum);
        Integer StrikeNum = sysOrderDeptService.count(new LambdaQueryWrapper<SysOrderDept>()
                .eq(SysOrderDept::getStatus, 1).eq(SysOrderDept::getDeptId, dept.getDeptId()).eq(SysOrderDept::getOrderStatus, 3));
        orderResponseVO.setStrikeNum(StrikeNum);


        List<SysOrderResponseDTO> validNum = sysOrderStrikeInvalidService.countBySql(dept.getDeptId());

        Map<Integer, Integer> map = validNum.stream().collect(Collectors.toMap(SysOrderResponseDTO::getDeptId, SysOrderResponseDTO::getCount, (oldValue, newValue) -> newValue));
        orderResponseVO.setValidNum(map.getOrDefault(1,0));
        orderResponseVO.setInValidNum(map.getOrDefault(0,0));

//        int invalidNum = sysOrderStrikeInvalidService.count(new LambdaQueryWrapper<SysOrderStrikeInvalid>()
//                .eq(SysOrderStrikeInvalid::getStatus, 1).eq(SysOrderStrikeInvalid::getDeptId, dept.getDeptId()).eq(SysOrderStrikeInvalid::getIsValid, 0));



        //orderResponseVO.setKvs();




        return orderResponseVO;
    }



    @Override
    public List<OrderDataResponseVO> data12() throws ParseException {
        List<OrderDataResponseVO> orderDataResponseVOS = new LinkedList<>();

        SysDept dept = tokenService.getLoginUser().getSysUser().getDept();
        if (dept == null) {
            throw new ServiceException("当前用户未分配组织！");
        }


        //查询最近12个月份
        List<String> last12Months = getLast12Months();

        List<OrderDataGroupResponseDTO>  list1 = sysOrderDeptService.selectCountGroupByMonth(dept.getDeptId());

        List<OrderDataGroupResponseDTO>  list2 = sysOrderStrikeInvalidService.selectCountGroupByMonth(dept.getDeptId());


        Map<String, Integer> map = list1.stream().collect(
                Collectors.toMap(OrderDataGroupResponseDTO::getYyyyMM, OrderDataGroupResponseDTO::getCount,(key1 , key2)-> key2 ));

        Map<String, Integer> map1 = list2.stream().collect(
                Collectors.toMap(OrderDataGroupResponseDTO::getYyyyMM, OrderDataGroupResponseDTO::getCount,(key1 , key2)-> key2 ));


//        List<SysOrderDept> list = sysOrderDeptService.list(new LambdaQueryWrapper<SysOrderDept>()
//                .eq(SysOrderDept::getStatus, 1).eq(SysOrderDept::getDeptId, dept.getDeptId()));

//        list.
//
//        orderResponseVO.setInStrikeNum(inStrikeNum);
//        Integer StrikeNum = sysOrderDeptService.count(new LambdaQueryWrapper<SysOrderDept>()
//                .eq(SysOrderDept::getStatus, 1).eq(SysOrderDept::getDeptId, dept.getDeptId()).eq(SysOrderDept::getOrderStatus, 3));
//        orderResponseVO.setStrikeNum(StrikeNum);

        for (String last12Month : last12Months) {

            OrderDataResponseVO orderDataResponseVO = new OrderDataResponseVO();
            orderDataResponseVO.setKey(last12Month);

            String lastMonth = getLastMonth(last12Month);
            HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();

            Integer count = sysOrderDeptService.selectCountBeforeMonth(lastMonth,dept.getDeptId());
            stringIntegerHashMap.put("orderTotal",count);

            stringIntegerHashMap.put("orderNumByMonth",map.getOrDefault(last12Month, 0));




            Integer count2 = sysOrderStrikeInvalidService.selectCountBeforeMonth(lastMonth,dept.getDeptId());
            stringIntegerHashMap.put("strikeTotal",count2);

            stringIntegerHashMap.put("strikeNumByMonth",map1.getOrDefault(last12Month, 0));

            orderDataResponseVO.setValue(stringIntegerHashMap);

            //当月核查数
//            Date date = DateUtils.parseDate(last12Month);
//
//            String lastDayOfCurrentMonth = DateUtil.endOfMonth(date).toString();
//            System.out.println(1);
            //
            //String endDate = DateUtils.parseDate(last12Month,"yyyy-MM-dd 23:59:59");
            orderDataResponseVOS.add(orderDataResponseVO);
        }
        return orderDataResponseVOS;
    }

    @Override
    public SysOrderSpeedRespVO speed(Integer orderId) {
        SysOrderSpeedRespVO sysOrderSpeedRespVO = new SysOrderSpeedRespVO();


        List<SysOrderSpeed> list = sysOrderSpeedService
                .list(new LambdaQueryWrapper<SysOrderSpeed>()
                        .eq(SysOrderSpeed::getStatus, 1)
                        .eq(SysOrderSpeed::getOrderId, orderId)
                        .orderByAsc(SysOrderSpeed::getPushLevel));



        if (!list.isEmpty()) {

            Map<Integer, Date> map = list.stream().collect(
                    Collectors.toMap(SysOrderSpeed::getPushLevel, SysOrderSpeed::getCreTime,(key1 , key2)-> key2 ));
            List<SysOrderSpeedRespVO.OrderSpeed> speeds = new ArrayList<>();

            for (OrderStatusEnum value : OrderStatusEnum.values()) {
                SysOrderSpeedRespVO.OrderSpeed speed = new SysOrderSpeedRespVO.OrderSpeed();
                speed.setDataKey(value.getDesc());
                Date date = map.getOrDefault(value.getCode(),null);
                if(date==null){
                    if(value.getCode() == 1 || value.getCode() == 2){
                        speed.setDataValue("待分发");
                    }
                    if(value.getCode() == 3){
                        speed.setDataValue("待核查");
                    }
                }else{
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    speed.setDataValue(simpleDateFormat.format(date));
                }

                speeds.add(speed);

            }
            sysOrderSpeedRespVO.setList(speeds);
        }
        return sysOrderSpeedRespVO;
    }


    public String getLastMonth(String last12Month){
        // 解析年月字符串
        LocalDate localDate = LocalDate.parse(last12Month + "-01");

        // 获取该月的最后一天
        LocalDate lastDayOfMonth = localDate.withDayOfMonth(localDate.lengthOfMonth());

        // 定义日期时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 格式化最后一天的日期时间
        String formattedDateTime = lastDayOfMonth.atTime(23, 59, 59).format(formatter);
        return formattedDateTime;
    }

    public static List<String> getLast12Months() {
        List<String> months = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        LocalDate currentDate = LocalDate.now();

        for (int i = 11; i >= 0; i--) {
            LocalDate month = currentDate.minusMonths(i);
            months.add(month.format(formatter));
        }

        return months;
    }



    private OrderSelectRequestDTO toDo(OrderSelectRequestVO vo) {
        OrderSelectRequestDTO orderSelectRequestDTO = new OrderSelectRequestDTO();
        orderSelectRequestDTO.setStart_time(vo.getStartTime());
        orderSelectRequestDTO.setEnd_time(vo.getEndTime());
        orderSelectRequestDTO.setKeyword(vo.getOrderKeyword());
        orderSelectRequestDTO.setOrder_status(vo.getOrderStatus());
        if("desc".equals(vo.getSortOrder())){
            orderSelectRequestDTO.setSortOrder(1);
        }else{
            orderSelectRequestDTO.setSortOrder(2);
        }

        return orderSelectRequestDTO;
    }


}




